package com.gyg.utils;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gyg
 * @version V1.0.0
 * @description:
 * @date 2020/12/29 16:36
 */
public class MapUtil {

    // 根据HashMap的value进行,type= 0 为升序，1为降序
    public static Map<String,Integer> sortMapByValue(Map<String,Integer> map,Integer type){
        Map<String, Integer> result = new LinkedHashMap<>();
        if (type == 0){
            map.entrySet().stream().sorted(Map.Entry.comparingByValue())
                    .forEachOrdered(x ->result.put(x.getKey(),x.getValue()));
        }else if (type == 1){
            map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .forEachOrdered(x ->result.put(x.getKey(),x.getValue()));
        }

        return result;
    }

    // 根据HashMap的key进行,type= 0 为升序，1为降序
    public static Map<String,String> sortMapByKey(Map<String,String> map,Integer type){
        Map<String, String> sortedMap = null;
        if (type == 0){
            sortedMap = map.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .collect(
                            Collectors.toMap(
                                    Map.Entry::getKey,
                                    Map.Entry::getValue,
                                    (oldVal, newVal) -> oldVal,
                                    LinkedHashMap::new
                            )
                    );
        }else if (type == 1){
            sortedMap = map.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .collect(
                            Collectors.toMap(
                                    Map.Entry::getKey,
                                    Map.Entry::getValue,
                                    (oldVal, newVal) -> newVal,
                                    LinkedHashMap::new
                            )
                    );
        }

        return sortedMap;
    }
}
